class Solution {
    public int minDistance(String word1, String word2) {
        /**
        还是考虑两个指针移动（边界）
        f[i][j] 表示 word1 的前i个字符 -> word2 的前j个字符需要的最少操作数
        有三种方式可以进行状态转移，分别是：插入，删除，替换
         */
        word1 = " " + word1;
        word2 = " " + word2;
        int m = word1.length();
        int n = word2.length();
        int[][] f = new int[m][n];
        int maxValue = m + n + 1;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                f[i][j] = maxValue;
            }
        }
        for (int i = 0; i < m; i++) f[i][0] = i;
        for (int j = 0; j < n; j++) f[0][j] = j;
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                int tmp = Math.min(f[i][j-1], f[i-1][j]);
                tmp++;
                if (word1.charAt(i) == word2.charAt(j)) {
                    f[i][j] = Math.min(tmp, f[i-1][j-1]);
                } else {
                    f[i][j] = Math.min(tmp, f[i-1][j-1] + 1);
                }
            }
        }
        return f[m-1][n-1];
    }
}
